<template>
  <div class="my-settings">
    <el-card class="settings-card">
      <div slot="header" class="card-header">
        <span>个人资料设置</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="头像" prop="image">
          <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.image" :src="form.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="个人介绍" prop="intro">
          <el-input
            type="textarea"
            v-model="form.intro"
            :rows="4"
            placeholder="介绍一下你自己吧"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="cellPhone">
          <el-input v-model="form.cellPhone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="QQ" prop="qq">
          <el-input v-model="form.qq" placeholder="请输入QQ号码"></el-input>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            placeholder="选择生日"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所在地" required>
          <el-col :span="8">
            <el-form-item prop="province">
              <el-input v-model="form.province" placeholder="省"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="city">
              <el-input v-model="form.city" placeholder="市"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="district">
              <el-input v-model="form.district" placeholder="区"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">保存修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="settings-card">
      <div slot="header" class="card-header">
        <span>账号安全</span>
      </div>
      <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            type="password"
            v-model="passwordForm.oldPassword"
            placeholder="请输入原密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            type="password"
            v-model="passwordForm.newPassword"
            placeholder="请输入新密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            type="password"
            v-model="passwordForm.confirmPassword"
            placeholder="请再次输入新密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="changePassword" :loading="changingPassword">修改密码</el-button>
          <el-button @click="resetPasswordForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="settings-card">
      <div slot="header" class="card-header">
        <span>通知设置</span>
      </div>
      <el-form :model="notificationSettings" label-width="100px">
        <el-form-item label="系统通知">
          <el-switch v-model="notificationSettings.system"></el-switch>
        </el-form-item>
        <el-form-item label="点赞提醒">
          <el-switch v-model="notificationSettings.likes"></el-switch>
        </el-form-item>
        <el-form-item label="评论提醒">
          <el-switch v-model="notificationSettings.comments"></el-switch>
        </el-form-item>
        <el-form-item label="收藏提醒">
          <el-switch v-model="notificationSettings.collections"></el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveNotificationSettings" :loading="savingNotifications">保存设置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from '@/config/http'

export default {
  name: 'UserSettings',
  data() {
    // 密码验证函数
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else if (value.length < 6) {
        callback(new Error('密码长度不能小于6位'))
      } else {
        if (this.passwordForm.confirmPassword !== '') {
          this.$refs.passwordForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    const validatePhone = (rule, value, callback) => {
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }

    const validateQQ = (rule, value, callback) => {
      if (value && !/^\d{5,11}$/.test(value)) {
        callback(new Error('请输入正确的QQ号码'))
      } else {
        callback()
      }
    }

    return {
      form: {
        userId: '',
        username: '',
        email: '',
        image: '',
        intro: '',
        gender: 0,
        cellPhone: '',
        qq: '',
        birthday: '',
        province: '',
        city: '',
        district: '',
        type: '',
        role: '',
        status: '',
        depId: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        cellPhone: [
          { validator: validatePhone, trigger: 'blur' }
        ],
        qq: [
          { validator: validateQQ, trigger: 'blur' }
        ],
        intro: [
          { max: 200, message: '个人介绍不能超过200个字符', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请输入省份', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '请输入城市', trigger: 'blur' }
        ],
        district: [
          { required: true, message: '请输入区域', trigger: 'blur' }
        ]
      },
      submitting: false,
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      },
      changingPassword: false,
      notificationSettings: {
        system: true,
        likes: true,
        comments: true,
        collections: true
      },
      savingNotifications: false
    }
  },
  created() {
    this.fetchUserInfo()
    this.fetchNotificationSettings()
  },
  methods: {
    async fetchUserInfo() {
      try {
        const { data } = await axios.get('/us/user/current')
        if (data.code === 0) {
          const userInfo = data.data.data
          // 将后端返回的数据映射到表单
          Object.keys(this.form).forEach(key => {
            if (userInfo[key] !== undefined) {
              this.form[key] = userInfo[key]
            }
          })
          // 更新到 Vuex store
          this.$store.dispatch('user/handleUserInfo', userInfo)
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.$message.error('获取用户信息失败')
      }
    },
    async fetchNotificationSettings() {
      try {
        const { data } = await axios.get('/pss/user/notification-settings')
        if (data.code === 0) {
          this.notificationSettings = data.data
        }
      } catch (error) {
        console.error('获取通知设置失败:', error)
        this.$message.error('获取通知设置失败')
      }
    },
    async handleAvatarSuccess(file) {
      try {
        // 创建 FormData 对象
        const formData = new FormData()
        formData.append('file', file.raw)  // 使用 file.raw 获取原始文件对象
        
        // 调用上传接口
        const result = await axios.post('/pss/images/upload', 
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        )
        
        if (result.data.code === 0) {
          // 获取上传后的图片URL
          const imageUrl = result.data.data
          
          // 更新表单数据
          this.form.image = imageUrl
          
          // 构建更新数据
          const updateData = {
            userId: this.form.userId,
            image: imageUrl
          }

          // 调用更新用户信息接口
          const { data } = await axios.put('/user/update', updateData)
          
          if (data.code === 0) {
            this.$message.success('头像更新成功')
            // 重新获取用户信息并更新到 store
            await this.fetchUserInfo()
          } else {
            this.$message.error(data.msg || '头像更新失败')
          }
        } else {
          this.$message.error(result.data.msg || '上传失败')
        }
      } catch (error) {
        console.error('头像更新失败:', error)
        this.$message.error('头像更新失败')
      }
    },
    beforeAvatarUpload(file) {
      const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG/PNG/GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    async submitForm() {
      try {
        await this.$refs.form.validate()
        this.submitting = true
        
        // 构建请求数据
        const updateData = {
          userId: this.form.userId,
          username: this.form.username,
          email: this.form.email,
          image: this.form.image,
          intro: this.form.intro,
          gender: this.form.gender,
          cellPhone: this.form.cellPhone,
          qq: this.form.qq,
          birthday: this.form.birthday,
          province: this.form.province,
          city: this.form.city,
          district: this.form.district,
          type: this.form.type,
          role: this.form.role,
          status: this.form.status,
          depId: this.form.depId
        }

        // 移除空值字段
        Object.keys(updateData).forEach(key => {
          if (updateData[key] === '' || updateData[key] === null || updateData[key] === undefined) {
            delete updateData[key]
          }
        })

        const { data } = await axios.put('/user/update', updateData)
        
        if (data.code === 0) {
          this.$message.success('保存成功')
          // 重新获取用户信息并更新到 store
          await this.fetchUserInfo()
        } else {
          this.$message.error(data.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败')
      } finally {
        this.submitting = false
      }
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.fetchUserInfo()
    },
    async changePassword() {
      try {
        await this.$refs.passwordForm.validate()
        this.changingPassword = true
        const { data } = await axios.put('/us/user/password', {
          oldPassword: this.passwordForm.oldPassword,
          newPassword: this.passwordForm.newPassword
        })
        if (data.code === 0) {
          this.$message.success('密码修改成功')
          this.resetPasswordForm()
        } else {
          this.$message.error(data.msg || '修改密码失败')
        }
      } catch (error) {
        console.error('修改密码失败:', error)
        this.$message.error('修改密码失败')
      } finally {
        this.changingPassword = false
      }
    },
    resetPasswordForm() {
      this.$refs.passwordForm.resetFields()
    },
    async saveNotificationSettings() {
      try {
        this.savingNotifications = true
        const { data } = await axios.put('/us/user/update', {
          userId: this.form.userId,
          notificationSettings: this.notificationSettings
        })
        if (data.code === 0) {
          this.$message.success('设置保存成功')
        } else {
          this.$message.error(data.msg || '保存设置失败')
        }
      } catch (error) {
        console.error('保存设置失败:', error)
        this.$message.error('保存设置失败')
      } finally {
        this.savingNotifications = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.my-settings {
  padding: 20px;

  .settings-card {
    margin-bottom: 20px;

    .card-header {
      font-size: 16px;
      font-weight: 600;
    }

    &:last-child {
      margin-bottom: 0;
    }
  }

  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;

      &:hover {
        border-color: #409eff;
      }
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }

    .avatar {
      width: 100px;
      height: 100px;
      display: block;
      object-fit: cover;
    }
  }

  :deep(.el-form-item) {
    margin-bottom: 22px;
  }

  :deep(.el-date-editor.el-input) {
    width: 100%;
  }
}
</style> 